"""
User views module
"""

from flask import Blueprint, request, g
from app.models.user import User
from app import db
from app.utils import ResponseUtil
from app.session_utils import require_auth, SessionManager
from app.controllers.user_controller import UserController

users_bp = Blueprint('users', __name__, url_prefix='/api/users')

@users_bp.route('/', methods=['GET'])
@require_auth
def get_current_user():
    """
    Get current user information (protected route)
    """
    try:
        user_id = g.current_user_id
        # Try to get user info from cache
        user_data = UserController.get_user_with_cache(user_id)
        
        if not user_data:
            return ResponseUtil.not_found(message="User not found")
        
        return ResponseUtil.success(data=user_data, message="User retrieved successfully")
    except Exception as e:
        return ResponseUtil.error(message="Failed to retrieve user", status_code=500)

@users_bp.route('/', methods=['PUT'])
@require_auth
def update_user():
    """
    Update current user (protected route)
    Only allows users to update their own information
    """
    try:
        # Get the current user ID from the session token
        user_id = g.current_user_id
        user = User.query.get(user_id)
        if not user:
            return ResponseUtil.not_found(message="User not found")
        
        data = request.get_json()
        if not data:
            return ResponseUtil.error(message="Request body is required", status_code=400)
        
        # Update user fields
        if 'username' in data:
            # Check if username is already taken by another user
            existing_user = User.query.filter_by(username=data['username']).first()
            if existing_user and existing_user.id != user_id:
                return ResponseUtil.error(message="Username already exists", status_code=409)
            user.username = data['username']
            
        if 'email' in data:
            # Check if email is already taken by another user
            existing_user = User.query.filter_by(email=data['email']).first()
            if existing_user and existing_user.id != user_id:
                return ResponseUtil.error(message="Email already exists", status_code=409)
            user.email = data['email']
            
        if 'status' in data:
            user.status = data['status']
            
        if 'background_image' in data:
            user.background_image = data['background_image']
            
        if 'avatar' in data:
            user.avatar = data['avatar']
            
        if 'user_group' in data:
            user.user_group = data['user_group']
        
        # Set audit field
        user.updated_by = user_id
        
        db.session.commit()
        
        # Update cached user info
        SessionManager.update_cached_user_info(user_id)
        
        # Return updated user data
        user_data = {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'status': user.status,
            'background_image': user.background_image,
            'avatar': user.avatar,
            'user_group': user.user_group,
            'created_at': user.created_at.isoformat() if user.created_at else None,
            'updated_at': user.updated_at.isoformat() if user.updated_at else None
        }
        
        return ResponseUtil.success(data=user_data, message="User updated successfully")
        
    except Exception as e:
        db.session.rollback()
        return ResponseUtil.error(message="Failed to update user", status_code=500)

@users_bp.route('/', methods=['DELETE'])
@require_auth
def delete_user():
    """
    Delete current user (protected route)
    Only allows users to delete their own account
    """
    try:
        # Get the current user ID from the session token
        user_id = g.current_user_id
        user = User.query.get(user_id)
        if not user:
            return ResponseUtil.not_found(message="User not found")
        
        # Set audit field
        user.deleted_by = user_id
        user.deleted_at = db.func.current_timestamp()
        
        db.session.commit()
        
        # Delete user session
        token = g.session_token
        SessionManager.delete_session(token)
        
        return ResponseUtil.success(message="User deleted successfully")
        
    except Exception as e:
        db.session.rollback()
        return ResponseUtil.error(message="Failed to delete user", status_code=500)